﻿//===============================================================================
// Microsoft patterns & practices Enterprise Library Contribution
// Resource Application Block
//===============================================================================

using System.Collections.Generic;
using Microsoft.Practices.EnterpriseLibrary.Common.Configuration.Unity;
using Microsoft.Practices.Unity;

namespace EntLibContrib.Resource.Configuration.Unity
{
	/// <summary>
	/// A <see cref="UnityContainerExtension"/> that registers the policies necessary
	/// to create <see cref="IResourceManager"/> instances described in the standard
	/// configuration file.
	/// </summary>
	public class ResourceBlockExtension : EnterpriseLibraryBlockExtension
	{
		#region Protected Methods
		/// <summary>
		/// Initialize this extension by adding the Enterprise Library Resource Block's policies.
		/// </summary>
		protected override void Initialize()
		{
			ResourceSettings settings = (ResourceSettings)ConfigurationSource.GetSection(ResourceSettings.SectionName);

			if (settings == null)
				return;

			CreateProvidersPolicies<IResourceManager, ResourceManagerDataBase>(Context.Policies,
																																				settings.DefaultResourceManager,
																																				settings.ResourceManagers,
																																				ConfigurationSource);

			CreateProvidersPolicies<IResourceProvider, ResourceProviderDataBase>(Context.Policies,
																																					null,
																																					settings.ResourceProviders,
																																					ConfigurationSource);

			CreateResourceManagerLifetimePolicies(Context.Container, settings.ResourceManagers);

			CreateResourceProviderLifetimePolicies(Context.Container, settings.ResourceProviders);
		}
		#endregion

		#region Private Static Methods
		private static void CreateResourceManagerLifetimePolicies(IUnityContainer container, IEnumerable<ResourceManagerDataBase> resourceManagers)
		{
			foreach (var resourceManagerData in resourceManagers)
			{
				container.RegisterType(resourceManagerData.Type, resourceManagerData.Name, new ContainerControlledLifetimeManager());
			}
		}

		private static void CreateResourceProviderLifetimePolicies(IUnityContainer container, IEnumerable<ResourceProviderDataBase> resourceProviders)
		{
			foreach (var resourceProviderData in resourceProviders)
			{
				container.RegisterType(resourceProviderData.Type, resourceProviderData.Name, new ContainerControlledLifetimeManager());
			}
		}
		#endregion
	}
}
